package com.tian.user.security;

import com.tian.common.util.SerializedObjectUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.stereotype.Component;
import com.tian.user.feign.AuthenFeignClient;
import com.tian.authen.api.feign.response.OauthAccessTokenResponse;

import java.util.Optional;

/**
 * @author zhump
 */
@Log4j2
@Component
public class IResourceServerTokenServices implements ResourceServerTokenServices {

    @Autowired
    private AuthenFeignClient feignClient;

    @Override
    public OAuth2Authentication loadAuthentication(String token) throws AuthenticationException, InvalidTokenException {
        log.info("[IResourceServerTokenServices],token:{}",token);
        OauthAccessTokenResponse bean = feignClient.getToken(token);
        Optional.ofNullable(bean).orElseThrow(()->new InvalidTokenException("认证失败,无效token"));
        OAuth2Authentication oAuth2Authentication = SerializedObjectUtils.serializedObject(bean.getAuthentication());
        Optional.ofNullable(oAuth2Authentication).orElseThrow(()->new InvalidTokenException("OAuth2Authentication serialized object is null"));
        return oAuth2Authentication;
    }

    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        log.info("[IResourceServerTokenServices]:readAccessToken:{}",tokenValue);
        return null;
    }
}
